package com.scalar.chiptrack.operations.dataentry.lotscrap.actioncommands;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.scalar.chiptrack.operations.dataentry.lotscrap.forms.ScrapMaterialForm;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.dataentry.dao.ScrapMaterialDAO;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.sales.SubTotal;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class ScrapMaterialSaveLotDetailsCommand  extends ActionCommand
{
    private static final String ACTION_NAME = "/scrapMaterial.do";


    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response ) throws Exception
    {
        ScrapMaterialForm scrapMaterialForm = ( ScrapMaterialForm ) form;

        HashMap errors               = new HashMap();
        HashMap info                 = new HashMap();

        ArrayList waferInfoList      = new ArrayList();
        String action                = request.getParameter ( "action" );

        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        HttpSession mSession              = request.getSession();
        User user                         = ( User ) mSession.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
        {
            mSession.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.SCRAP_MATERIAL , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

        LotDetails scrapLotsDetails = null;
        LotDetails sortBinlotDetails = null;

        if ( "save".equalsIgnoreCase( action ) )
        {
            LinkedHashMap hash = new LinkedHashMap();
            ArrayList arrList  = new ArrayList();

           //for Confirm Screen
            for (int i = 0; i < scrapMaterialForm.getWipLotsList().size(); i++)
            {
                scrapLotsDetails = (LotDetails) scrapMaterialForm.getWipLotsList().get(i);

                if ( scrapLotsDetails.isChecked() )
                {                       
                    if ( scrapLotsDetails.getCheckedWaferIdsAsString() == null || scrapLotsDetails.getCheckedWaferIdsAsString().equals("") )
                    {
                        scrapLotsDetails.setCheckedWaferIdsAsString( scrapLotsDetails.getWaferIds() );
                        scrapLotsDetails.setCheckedScrapQtyAsString( scrapLotsDetails.getScrapQtyAsString() );
                    }
                    if ( LOCATION_TYPE_FAB.equalsIgnoreCase( scrapMaterialForm.getBaseprocessType() ) || LOCATION_TYPE_WAFER_STORE.equalsIgnoreCase( scrapMaterialForm.getBaseprocessType() )
                             || LOCATION_TYPE_SORT.equalsIgnoreCase( scrapMaterialForm.getBaseprocessType() ) || LOCATION_TYPE_BUMPING.equalsIgnoreCase( scrapMaterialForm.getBaseprocessType() )   )
                    {
                          scrapLotsDetails.setScrapDieQty( Integer.parseInt(scrapLotsDetails.getShipQty()) );
                    }
                    if (LOCATION_TYPE_DIE_BANK.equalsIgnoreCase( scrapMaterialForm.getBaseprocessType() ) )
                    {
                        // TO UPDATE THE BIN QTY'S
                        sortBinlotDetails = new LotDetails();
                        sortBinlotDetails.setLotId( scrapLotsDetails.getLotId() );
                        sortBinlotDetails.setCheckedWaferIdsAsString( scrapLotsDetails.getCheckedWaferIdsAsString() );
                        sortBinlotDetails.setCheckedScrapQtyAsString( scrapLotsDetails.getCheckedScrapQtyAsString() );

                        waferInfoList.add( sortBinlotDetails );
                    }

                    String partNumber = scrapLotsDetails.getPartNumber();
                    if ( !( hash.containsKey ( partNumber ) ) )
                    {
                        hash.put ( partNumber, new ArrayList() );
                    }
                    arrList = (ArrayList) hash.get ( partNumber );

                    arrList.add ( scrapLotsDetails );
                }
            }

            Iterator iterator = hash.keySet().iterator();
            LinkedHashMap hashMap = new LinkedHashMap ();

            while ( iterator.hasNext () )
            {
                String str = ( String ) iterator.next ();
                ArrayList newarrList = ( ArrayList )hash.get ( str );
                SubTotal subTotal = new SubTotal();
                int subTotalQty = 0;

                for ( int j = 0; j < newarrList.size (); j++ )
                {
                    if ( scrapMaterialForm.isNonValueInventory() )
                    {
                        subTotalQty = subTotalQty + Integer.parseInt( ( (LotDetails)newarrList.get( j ) ).getDieQtyIn() ) ;
                    }
                    else
                    {
                       subTotalQty = subTotalQty + ( (LotDetails)newarrList.get( j ) ).getScrapDieQty() ;
                    }
                }
                subTotal.setSubTotalQty( Integer.toString ( subTotalQty )  );

                hashMap.put ( newarrList, subTotal );
            }

            request.setAttribute("subTotalMap", hashMap );

            scrapMaterialForm.setWaferInfoList(  waferInfoList );

            request.setAttribute("action", action);

            saveToken( request );
            return mapping.findForward( "scrapMaterialConfirm" );
        }
        else
        {
            if ( isTokenValid( request ))
            {
                try
                {
                    if ( scrapMaterialForm.isNonValueInventory() )
                    {
                        //ScrapMaterialDAO.moveNonValueInvetoryToWip( null, scrapMaterialForm.getWipLotsList(), user.getUserName() );
                        ScrapMaterialDAO.moveNonValueInvetoryToScrap( null, scrapMaterialForm.getWipLotsList(), user.getUserName() );

                        if ( scrapMaterialForm.getWaferInfoList() != null && scrapMaterialForm.getWaferInfoList().size() > 0 )
                        {
                            ScrapMaterialDAO.updateDieBankNonValueBinInfo( null, scrapMaterialForm.getWaferInfoList() );
                        }
                        resetToken( request );
                        info.put ( "Non ValueInventory Lots Moved to SCRAP Successfully ", null );
                    }
                    else
                    {
                        ScrapMaterialDAO.saveScrappedLotDetails( null, scrapMaterialForm.getWipLotsList(), user.getUserName() );

                        if ( scrapMaterialForm.getWaferInfoList() != null && scrapMaterialForm.getWaferInfoList().size() > 0 )
                        {
                            ScrapMaterialDAO.updateDieBankScrappedBinInfo( null, scrapMaterialForm.getWaferInfoList() );
                        }
                        resetToken( request );
                        info.put ( "Lot Scrapped Information Saved Successfully ", null );

                    }
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    errors.put( "Error storing the Scrapped Lot information", null );
                }
            }
            else
            {
                 errors.put("Invalid Request" , null );
            }

            scrapMaterialForm.setProcessType("0");
            scrapMaterialForm.setProcessStepId(0);
            scrapMaterialForm.setLocationId(0);
            scrapMaterialForm.setLotId(0);
            scrapMaterialForm.setWipLotsList( null );

            request.setAttribute("processTypes", NewProductDAO.loadAllProcessesFromDB(null, false) );
            request.setAttribute("action", action);
        }

        return mapping.findForward( "scrapMaterial" );

    }
}